package algorithm.map;


import java.util.ArrayList;

/**
 * @author bingo
 * @Description
 * @Date 2018/7/9
 */
public class BSTMap<K extends Comparable<K>,V> implements  Map<K,V> {

    private BinarySearchTree bis;

    private Integer size;

    public BSTMap() {
        this.bis =  new BinarySearchTree();
        size = 0;
    }

    @Override
    public void add(K key, V value) {
        bis.insert(key,value);
        size++;
    }

    @Override
    public void set(K key, V value) {
        boolean  flag = bis.contain(key);
        if(!flag){
           throw  new IllegalArgumentException("don't have the key named "+key);
        }

        bis.insert(key,value);
    }

    @Override
    public V remove(K key) {
      BinarySearchTree.Node res =  bis.removeNode(key);
       size--;
       return (V) res.value;
    }

    @Override
    public V get(K key) {
   return (V) bis.search(key);
    }

    @Override
    public boolean contains(K key) {
        return bis.contain(key);
    }

    public Integer getSize() {
        return size;
    }

    public static void main(String[] args){
        System.out.println("Pride and Prejudice");
        ArrayList<String> words = new ArrayList<>();
        if(FileOperation.readFile("demo/pride-and-prejudice.txt", words)) {
            System.out.println("Total words: " + words.size());
            BSTMap<String, Integer> map = new BSTMap<>();
            for (String word : words) {
                if (map.contains(word))
                    map.set(word, map.get(word) + 1);
                else
                    map.add(word, 1);
            }
            System.out.println("Total different words: " + map.getSize());
            System.out.println("Frequency of PRIDE: " + map.get("pride"));
            System.out.println("Frequency of PREJUDICE: " + map.get("prejudice"));
        }

        System.out.println("2^3=");
    }
}
